<script setup lang="ts">
  import { getCurrentInstance, reactive, ref } from 'vue'
  import { reqAuthUserSelectAllUrl, reqRoleAuthUserUnAllocatedListUrl } from '@/api/system/role'
  import { ElMessage, ElTable, FormInstance } from 'element-plus'

  /*获取父组件传递来的信息*/
  const props = defineProps({
    roleId: {
      type: Number,
      required: true,
    },
  })

  let $emit = defineEmits(['ok'])
  const { proxy }: any = getCurrentInstance()
  const userList = ref()
  const total = ref(0)
  const queryFormRef = ref<FormInstance>() /*查询表单的Ref*/
  const queryParams = reactive({
    roleId: '',
    pageNum: 1,
    pageSize: 5,
    username: '',
    phonenumber: '',
  })
  const dialogVisible = ref(false) /*对话框框开关*/
  const table = ref<InstanceType<typeof ElTable>>()
  const userIds = ref([]) // 选中数组值
  const initFormData = () => {
    console.log('打开对话框')
    dialogVisible.value = true
    getUnList()
  }

  /*进行查询*/
  const handleQuery = async () => {
    queryParams.pageNum = 1
    table.value.clearSelection()
    await getUnList()
  }
  // 重置表单
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    Object.keys(queryParams).forEach((key) => {
      if (key === 'pageNum') {
        queryParams[key] = 1
      } else if (key === 'pageSize') {
        queryParams[key] = 10
      } else {
        queryParams[key] = ''
      }
    })
  }

  // 获取未授予该角色权限的用户
  const getUnList = async () => {
    queryParams.roleId = props.roleId
    await reqRoleAuthUserUnAllocatedListUrl(queryParams)
      .then((response) => {
        userList.value = response.rows
        total.value = response.total
      })
      .catch((e) => {
        ElMessage.error(e)
      })
  }

  /*当点击行时，进行选中操作*/
  const clickRow = (row: any, column, event) => {
    const findIndex = userIds.value.indexOf(row.userId)
    if (findIndex == -1) {
      /*userIds中没有userId*/
      table.value.toggleRowSelection(row, true)
    } else {
      /*说明已经存在了进行移除*/
      table.value.toggleRowSelection(row, false)
    }
  }

  /*多选框选中数据*/
  const handleSelectionChange = (selection: any) => {
    userIds.value = selection.map((item: any) => item.userId) /*将多选框选中后的数据放到userIds中*/
  }

  /*提交按钮*/
  const handleSelectUser = async () => {
    const roleId = queryParams.roleId
    const user_Ids = userIds.value.join(',')
    /*如果没有选中*/
    if (user_Ids == '' || user_Ids == null) {
      proxy.$modal.msgError('请选择要分配的用户！')
      return
    }
    /*进行添加操作*/
    await reqAuthUserSelectAllUrl({ roleId: roleId, userIds: user_Ids }).then((res) => {
      if (res.code === 200) {
        /*添加成功*/
        proxy.$modal.msgSuccess(res.message)
        dialogVisible.value = false
        table.value.clearSelection()
        $emit('ok')
      } else {
        proxy.$modal.msgError(res.message)
      }
    })
  }

  //主动暴露childMethod方法
  defineExpose({ initFormData })
</script>

<template>
  <el-dialog title="选择用户" v-model="dialogVisible" width="80%" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryFormRef" size="default" :inline="true">
      <el-form-item label="用户名称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="default" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery"> 重置 </el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-table
        @row-click="clickRow"
        ref="table"
        :data="userList"
        row-key="userId"
        @selection-change="handleSelectionChange"
        height="300px"
      >
        <el-table-column
          type="selection"
          width="55"
          key="userId"
          :reserve-selection="true"
        ></el-table-column>
        <el-table-column label="用户名称" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
        <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status">
          <template v-slot="scope">
            <!--            <DictTag
              :options="dict.type.sys_normal_disable"
              :value="scope.row.status"
            ></DictTag>-->
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        ></el-table-column>
      </el-table>
      <el-pagination
        v-show="total > 0"
        background
        layout="prev, pager, next"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        @current-change="getUnList"
      ></el-pagination>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="handleSelectUser">确 定</el-button>
        <el-button type="warning" @click="dialogVisible = false"> 取 消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
  export default {
    dicts: ['sys_normal_disable'],
  }
</script>

<style scoped lang="scss"></style>
